/// <reference path="../types/wechat.d.ts" />
import axios from 'axios'
import type { WechatJSSDKConfig, WechatUserInfo } from '@/types/wechat'

// 微信授权相关配置（从环境变量获取）
export const WECHAT_CONFIG = {
  // 微信公众号AppID
  appId: import.meta.env.VITE_WECHAT_APP_ID || 'YOUR_WECHAT_APP_ID',
  // 授权回调域名
  redirectUri: encodeURIComponent(import.meta.env.VITE_REDIRECT_URI || window.location.origin),
  // 授权作用域
  scope: 'snsapi_userinfo',
  // 防CSRF的state（生产建议由后端下发或使用更随机的值）
  state: 'STATE',
}

/**
 * 是否在微信内置浏览器中
 */
export const isWechatBrowser = (): boolean => {
  const ua = navigator.userAgent.toLowerCase()
  return ua.includes('micromessenger')
}

/**
 * 获取URL查询参数
 */
export const getUrlParam = (name: string): string | null => {
  const urlParams = new URLSearchParams(window.location.search)
  return urlParams.get(name)
}

/**
 * 构建微信网页授权URL
 */
export const buildWechatAuthUrl = (): string => {
  const { appId, redirectUri, scope, state } = WECHAT_CONFIG
  return `https://open.weixin.qq.com/connect/oauth2/authorize?appid=${appId}&redirect_uri=${redirectUri}&response_type=code&scope=${scope}&state=${state}#wechat_redirect`
}

/**
 * 跳转到微信授权
 */
export const redirectToWechatAuth = (): void => {
  if (!isWechatBrowser()) {
    throw new Error('请在微信中打开此页面')
  }
  window.location.href = buildWechatAuthUrl()
}

/**
 * 使用code向后端交换用户信息
 * 注意：需要后端服务调用微信接口（携带AppSecret），前端仅调用自家API
 */
export const getUserInfoByCode = async (code: string): Promise<WechatUserInfo> => {
  const resp = await axios.post('/api/wechat/getUserInfo', { code })
  return resp.data as WechatUserInfo
}

/**
 * 初始化微信JS-SDK
 */
export const initWechatJSSDK = (config: WechatJSSDKConfig): Promise<void> => {
  return new Promise((resolve, reject) => {
    if (typeof wx === 'undefined') {
      reject(new Error('微信JS-SDK未加载'))
      return
    }

    wx.config({
      debug: false,
      appId: config.appId,
      timestamp: config.timestamp,
      nonceStr: config.nonceStr,
      signature: config.signature,
      jsApiList: [
        'updateAppMessageShareData',
        'updateTimelineShareData',
        'onMenuShareTimeline',
        'onMenuShareAppMessage',
        'chooseImage',
        'uploadImage',
      ],
    })

    wx.ready(() => resolve())
    wx.error(() => reject(new Error('微信JS-SDK初始化失败')))
  })
}

/**
 * 向后端获取微信JS-SDK签名配置
 */
export const getWechatJSSDKConfig = async (): Promise<WechatJSSDKConfig> => {
  const resp = await axios.post('/api/wechat/getJSSDKConfig', {
    url: window.location.href.split('#')[0],
  })
  return resp.data as WechatJSSDKConfig
}

/**
 * 设置微信分享参数
 */
export const setWechatShare = (shareData: Partial<{ title: string; desc: string; link: string; imgUrl: string }>): void => {
  if (typeof wx === 'undefined') {
    console.warn('微信JS-SDK未加载，无法设置分享')
    return
  }

  const defaultShareData = {
    title: '微信公众号H5应用',
    desc: '欢迎使用我们的H5应用',
    link: window.location.href,
    imgUrl: window.location.origin + '/logo.png',
    ...shareData,
  }

  // 分享给朋友
  wx.updateAppMessageShareData({
    title: defaultShareData.title,
    desc: defaultShareData.desc,
    link: defaultShareData.link,
    imgUrl: defaultShareData.imgUrl,
    success: () => {},
  })

  // 分享到朋友圈
  wx.updateTimelineShareData({
    title: defaultShareData.title,
    link: defaultShareData.link,
    imgUrl: defaultShareData.imgUrl,
    success: () => {},
  })
}
